package org.example;

import org.openjdk.jol.info.ClassLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class BulkBias {

    private static Thread t1, t2;

    public static void main(String[] args) throws InterruptedException {
        // 延时产生可偏向对象
        TimeUnit.SECONDS.sleep(5);

        List<B> objects = new ArrayList<>(); // 创建50个对象，锁状态为101，匿名偏向锁
        for (int i = 0; i < 50; i++) {
            objects.add(new B());
        }

        t1 = new Thread(() -> {
            for (int i = 0; i < objects.size(); i++) {
                synchronized (objects.get(i)) { // 50个对象全部偏向t1 101
                }
            }
            LockSupport.unpark(t2);
        });

        t2 = new Thread(() -> {
            LockSupport.park();
            //这里面只循环了30次！！！
            for (int i = 0; i < 30; i++) {
                Object a = objects.get(i);
                synchronized (a) {
                    //分别打印第19次和第20次偏向锁重偏向结果
                    if (i == 18 || i == 19) {
                        System.out.println("第" + (i + 1) + "次偏向结果");
                        System.out.println((ClassLayout.parseInstance(a).toPrintable())); // 第19次轻量级锁00，第20次偏向锁101，偏向t2
                    }
                }
            }
        });
        t1.start();
        t2.start();
        t2.join();

        System.out.println("打印list中第11个对象的对象头：");
        System.out.println((ClassLayout.parseInstance(objects.get(10)).toPrintable())); // 01 无锁
        System.out.println("打印list中第26个对象的对象头：");
        System.out.println((ClassLayout.parseInstance(objects.get(25)).toPrintable())); // 101 偏向t2
        System.out.println("打印list中第41个对象的对象头：");
        System.out.println((ClassLayout.parseInstance(objects.get(40)).toPrintable())); // 101 偏向t1
    }
}

